package com.sky.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.EmployeeCreateException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.crypto.ExemptionMechanismException;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeMapper employeeMapper;

    public EmployeeServiceImpl(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 明文密码md5加密储存
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * @param employeeDTO
     */
    @Override
    public void create(EmployeeDTO employeeDTO) {
        Integer count = employeeMapper.selectCount(employeeDTO.getUsername());
        if (count > 0) {
            throw new EmployeeCreateException(MessageConstant.REPEAT_USER_NAME);
        }
        if (Objects.isNull(employeeDTO.getPhone()) || employeeDTO.getPhone().length() != 11) {
            throw new EmployeeCreateException(MessageConstant.ERROR_PHONE);
        }
        if (Objects.isNull(employeeDTO.getIdNumber()) || employeeDTO.getIdNumber().length() != 18) {
            throw new EmployeeCreateException(MessageConstant.ERROR_ID_NUMBER);
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        String md5Password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(md5Password);
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.insert(employee);
    }

    /**
     * @param employeePageQueryDTO
     * @return {@link PageResult}
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.selectListByName(employeePageQueryDTO.getName());
        PageInfo<Employee> pageInfo = PageInfo.of(employeeList);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        Employee employee = employeeMapper.selectById(id);
        employee.setStatus(status);
        employeeMapper.update(employee);
    }

    /**
     * @param id
     * @return {@link Employee}
     */
    @Override
    public Employee queryById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword(null);
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Integer count = employeeMapper.selectCountByUsernameNotSelf(employeeDTO.getUsername(), employeeDTO.getId());
        if (count > 0) {
            throw new EmployeeCreateException(MessageConstant.REPEAT_USER_NAME);
        }
        if (Objects.isNull(employeeDTO.getPhone()) || employeeDTO.getPhone().length() != 11) {
            throw new EmployeeCreateException(MessageConstant.ERROR_PHONE);
        }
        if (Objects.isNull(employeeDTO.getIdNumber()) || employeeDTO.getIdNumber().length() != 18) {
            throw new EmployeeCreateException(MessageConstant.ERROR_ID_NUMBER);
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.update(employee);
    }

}
